package com.mybatis.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author nmm
 * @date 2024-02-2024/2/29
 * @deriction njm......
 */
public class SqlSessionUtil {
    public SqlSessionUtil() {
    }

    private  static SqlSessionFactory sqlSessionFactory;

    private  static  ThreadLocal<SqlSession> local=new ThreadLocal<>();
    //SqlSession 为什么放到ThreadLocal中,为了保证一个线程对应一个Sqlsession
    //全局的,服务器级别的,一个服务器中定义一个即可

     static {
         try {
             sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
         } catch (IOException e) {
             throw new RuntimeException(e);
         }
     }

    public  static  SqlSession  opensession() {
     SqlSession sqlSession=local.get();
        if (sqlSession==null) {
            sqlSession=sqlSessionFactory.openSession();
            local.set(sqlSession);//将sqlSession对象绑定当前线程
        }
        return sqlSession;
     }

     public static void close(SqlSession sqlSession) {
         if (sqlSession != null) {
             sqlSession.close();
             local.remove();//从当前线程中移除sqlSession对象
         }
     }

}